using System;
using System.Data;
using System.Configuration;

namespace Log2SQL
{
    public class NCSALogImport : LogImport
    {
        public NCSALogImport() : base()
        {
        }

        //172.21.13.45 - Microsoft\JohnDoe [08/Apr/2001:17:39:04 -0800] "GET /scripts/iisadmin/ism.dll?http/serv HTTP/1.0" 200 3401

        protected override void ProcessLine(string line)
        {
            base.ProcessLine(line);

            //create table (if it is not created allready!!!)
            if (!_isTableCreated)
            {
                string[] fields = new string[7] { "host", "rfc931", "username", "request-date", "request", "statuscode", "bytes" };
                SQLCreateTable(_tableNameToWriteTo, fields);
                _isTableCreated = true;
            }

            //write values to the table
            string host, rfc931, username, requestdate, request, statuscode, bytes;
            
            host = line.Substring(0, line.IndexOf(" "));
            line = line.Substring(host.Length + 1);

            rfc931 = line.Substring(0, line.IndexOf(" "));
            line = line.Substring(rfc931.Length + 1);

            username = line.Substring(0, line.IndexOf(" "));
            line = line.Substring(username.Length + 2); //!!! +2 to delete the first "[" here

            requestdate = line.Substring(0, line.IndexOf("]"));
            line = line.Substring(requestdate.Length + 3); //!!! +3 again to delete this: '] "'

            request = line.Substring(0, line.IndexOf("\""));
            line = line.Substring(request.Length + 2); //+2 to remove '" '

            statuscode = line.Substring(0, line.IndexOf(" "));
            bytes = line.Substring(line.IndexOf(" ") + 1);

            string[] values = new string[7] { host, rfc931, username, requestdate, request, statuscode, bytes };
            SQLInsertValues(_tableNameToWriteTo, values);
        }
    }
}
